package com.xike.micromemberserver.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xike.entiy.ResultBean;
import com.xike.micromemberserver.entity.BooksEntity;
import com.xike.micromemberserver.entity.ChapterEntity;
import com.xike.micromemberserver.entity.PageInfoMation;
import com.xike.micromemberserver.feign.MessageFeign;
import com.xike.micromemberserver.service.IBooksService;
import com.xike.micromemberserver.service.IChapterService;
import com.xike.micromemberserver.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;

import java.io.*;
import java.util.List;

/**
 * @author hongbin
 * @date 2021-04-28 19:07
 * Description：
 */
@Api("图书管理")
@RestController
@RequestMapping("/member/books")
public class BooksController {
    @Resource
    private IBooksService booksService;
    @Autowired(required = false)
    private LoginService loginService;
    @Resource
    private IChapterService chapterService;
    @Resource
    private MessageFeign messageFeign;


    @ApiOperation("查询所有图书status=1")
    @PostMapping("/selectAll")
    public ResultBean selectAll(@RequestBody PageInfoMation pageInfo){
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getLimit());
        List<BooksEntity> booksEntities = booksService.selectAll();
        PageInfo<BooksEntity> books = new PageInfo<>(booksEntities);
        return ResultBean.builder().code(200).msg("OK").data(books).build();
    }

    @ApiOperation("按阅读量查询所有图书status=1")
    @PostMapping("/selectAllByvisits")
    public ResultBean selectAllByvisits(@RequestBody PageInfoMation pageInfo){
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getLimit());
        List<BooksEntity> booksEntities = booksService.selectAllByvisits();
        PageInfo<BooksEntity> books = new PageInfo<>(booksEntities);
        return ResultBean.builder().code(200).msg("OK").data(books).build();
    }

    @ApiOperation("查询所有下架图书status=3")
    @PostMapping("/selectAlloff")
    public ResultBean selectAlloff(@RequestBody PageInfoMation pageInfo){
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getLimit());
        List<BooksEntity> booksEntities = booksService.selectAlloff();
        PageInfo<BooksEntity> books = new PageInfo<>(booksEntities);
        return ResultBean.builder().code(200).msg("OK").data(books).build();
    }

    @ApiOperation("新增图书")
    @PostMapping("/insert")
    public ResultBean insert(@RequestBody BooksEntity booksEntitie){
        booksService.insert(booksEntitie);
        return ResultBean.builder().code(200).msg("OK").build();
    }
    @ApiOperation("增加阅读量")
    @PostMapping("/addVisits")
    public ResultBean addVisits(@RequestBody BooksEntity booksEntitie){
        booksService.addVisits(booksEntitie.getId());
        return ResultBean.builder().code(200).msg("OK").build();
    }

    @ApiOperation("整本上传")
    @PostMapping("/uploadAll")
    public ResultBean uploadAll(@RequestBody BooksEntity booksEntitie){
// Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-chengdu.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        String accessKeyId = "LTAI4G5jxxYQcZ3YxECYjvoA";
        String accessKeySecret = "NamE0K84zAgozWCrUmVkvS9WsGhUFA";
        String bucketName = "wusong01";
// <yourObjectName>从OSS下载文件时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
//        String objectName ="Objtest.txt";https://wusong01.oss-cn-chengdu.aliyuncs.com/Objtest.txt
        String[] split = booksEntitie.getSrc().split("/");
        String objectName =split[split.length-1];
        System.out.println(objectName);
// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, objectName);

// 读取文件内容。%E7%9B%97%E5%A2%93%E7%AC%94%E8%AE%B0.txt
        System.out.println("Object content:");
        BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
       //增加新书
        booksService.insert(booksEntitie);
        BooksEntity newBooksEntity = booksService.selectByNameUnApproval(PageInfoMation.builder().bookName(booksEntitie.getBookName()).build()).get(0);
        int id = newBooksEntity.getId();
        //每一章的内容
        StringBuilder content = new StringBuilder();
        //当前章节数
        int currentChapterNum = 0;
        //上一章标题
        StringBuilder proTitle = new StringBuilder();

        while (true) {
            String line = null;
            try {
                line = reader.readLine();

            } catch (IOException e) {
                e.printStackTrace();
            }
            if (line == null) break;
            String splits[] = null;
            content.append(line);

                System.out.println(line);

            if(line.matches("第([0-9]|一|二|三|四|五|六|七|八|九|十|百|千|零){1,9}章")||
               (splits = line.split("第([0-9]|一|二|三|四|五|六|七|八|九|十|百|千|零){1,9}章")).length>1

            ){
                //新章节标题
                StringBuilder newTitle = new StringBuilder();
                //新章节名

                    newTitle.append("    "+line.trim());

                //如果是第一章以前的内容跳过
                if(currentChapterNum==0){
                    //清除上一章的content内容
                    content.delete(0,content.length());
                    //章节数加一
                    currentChapterNum +=1;
                    continue;
                }
                //存储上一章内容
                chapterService.insert(ChapterEntity.builder().bookId(id).chapterNum(currentChapterNum).title(proTitle.toString()
                ).content(content.toString()).build());
                //清除上一章的content内容
                content.delete(0,content.length());
                proTitle.delete(0,proTitle.length());
                //吧当前章节名存入上一章节名
                proTitle = newTitle;
                currentChapterNum +=1;

            }

        }
// 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

// 关闭OSSClient。
        ossClient.shutdown();
        return ResultBean.builder().code(200).msg("OK").build();
    }

    @ApiOperation("审批图书")
    @PostMapping("/approval")
    public ResultBean approval(@RequestBody BooksEntity booksEntitie){
        BooksEntity currentBooksEntity = booksService.selectById(booksEntitie.getId());
        if(booksEntitie.getStatus()==3){
            String msg = "您上传的图书："+currentBooksEntity.getBookName()+"审批失败，详情请联系管理员";
//            messageFeign.sendMessage(booksEntitie.getUploader(),msg);
            booksService.approvalBook(booksEntitie);
            return ResultBean.builder().code(200).msg("审批结果：失败").build();
        }
        booksService.approvalBook(booksEntitie);
        return ResultBean.builder().code(200).msg("审批成功，已上架").build();
    }

    @ApiOperation("通过id修改任意字段")
    @PostMapping("/update")
    public ResultBean update(@RequestBody BooksEntity booksEntity){
        booksService.update(booksEntity);
        return ResultBean.builder().code(200).msg("OK").build();
    }
    @ApiOperation("通过id删除")
    @PostMapping("/delete")
    public ResultBean delete(@RequestBody BooksEntity booksEntity){
        booksService.delete(booksEntity.getId());
        return ResultBean.builder().code(200).msg("OK").build();
    }
    @ApiOperation("书名模糊查询")
    @PostMapping("/selectByName")
    public ResultBean selectByName(@RequestBody PageInfoMation pageInfo){
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getLimit());
        List<BooksEntity> booksEntities = booksService.selectByName(pageInfo);
        PageInfo<BooksEntity> books = new PageInfo<>(booksEntities);
        return ResultBean.builder().code(200).msg("OK").data(books).build();
    }

    @ApiOperation("书类型模糊查询")
    @PostMapping("/selectByType")
    public ResultBean selectByType(@RequestBody PageInfoMation pageInfo){
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getLimit());
        List<BooksEntity> booksEntities = booksService.selectByType(pageInfo);
        PageInfo<BooksEntity> books = new PageInfo<>(booksEntities);
        return ResultBean.builder().code(200).msg("OK").data(books).build();
    }

    @ApiOperation("书名时间模糊查询未上架图书")
    @PostMapping("/selectByNameUnApproval")
    public ResultBean selectByNameUnApproval(@RequestBody PageInfoMation pageInfo){
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getLimit());
        List<BooksEntity> booksEntities = booksService.selectByNameUnApproval(pageInfo);
        PageInfo<BooksEntity> books = new PageInfo<>(booksEntities);
        return ResultBean.builder().code(200).msg("OK").data(books).build();
    }

    @ApiOperation("书名作者模糊查询")
    @PostMapping("/selectByAny")
    public ResultBean selectByAny(@RequestBody PageInfoMation pageInfo){
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getLimit());
        List<BooksEntity> booksEntities = booksService.selectByAny(pageInfo.getKeyword());
        PageInfo<BooksEntity> books = new PageInfo<>(booksEntities);
        return ResultBean.builder().code(200).msg("OK").data(books).build();
    }

    @ApiOperation("查询未上架图书")
    @PostMapping("/selectUnApproval")
    public ResultBean  selectUnApproval(@RequestBody PageInfoMation pageInfo){
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getLimit());
        List<BooksEntity> booksEntities = booksService.selectUnApproval(pageInfo);
        PageInfo<BooksEntity> books = new PageInfo<>(booksEntities);
        return ResultBean.builder().code(200).msg("OK").data(books).build();
    }

    @ApiOperation("查询我上传的图书")
    @PostMapping("/selectByUploader")
    public ResultBean selectByUploader(@RequestBody PageInfoMation pageInfo){
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getLimit());
        List<BooksEntity> booksEntities = booksService.selectByUploader(pageInfo);
        PageInfo<BooksEntity> books = new PageInfo<>(booksEntities);
        return ResultBean.builder().code(200).msg("OK").data(books).build();
    }
    @ApiOperation("通过id查询图书")
    @PostMapping("/selectByid")
    public ResultBean selectByid(@RequestBody BooksEntity booksEntity){
        List<BooksEntity> booksEntities = booksService.selectByid(booksEntity.getId());
        PageInfo<BooksEntity> books = new PageInfo<>(booksEntities);
        return ResultBean.builder().code(200).msg("OK").data(books).build();
    }
}
